<?php
namespace Opportunity\Model;

use Zend\Db\TableGateway\TableGateway;

class OpportunityTable 
{
    protected $tableGateway;

	public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function getOpportunity($id)
    {
    	$id  = (int) $id;
    	$rowset = $this->tableGateway->select(array('id' => $id));
    	$row = $rowset->current();
    	if (!$row) {
    		throw new \Exception("Could not find row $id");
    	}
    	return $row;
    }
    
	public function saveOpportunity(Opportunity $opportunity)
    {
        $data = array(
            // 'id' => $opportunity->id,
        		'name'  => $opportunity->name,
        		'amount_currency_id'  => $opportunity->amount_currency_id,
        		'amount_value'  => $opportunity->amount_value,
        		'account_id' => $opportunity->account_id,
        		'closedate'  => $opportunity->closedate,
        		'stage_id' => $opportunity->stage_id,
        		'probability' => $opportunity->probability,
        		'source_id'  => $opportunity->source_id,
				'description' => $opportunity->description,
            
        );

        $id = (int)$opportunity->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getOpportunity($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }
    
    public function deleteOpportunity($id)
    {
    	$this->tableGateway->delete(array('id' => $id));
    }
}
?>